package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.ruoyi.system.config.AliPayConfig;
import com.ruoyi.system.domain.dto.AliPayDTO;
import com.ruoyi.system.domain.dto.BillUsageVo;
import com.ruoyi.system.mapper.BillInfoMapper;
import com.ruoyi.system.service.IAliPayService;
import com.ruoyi.system.utils.MyMath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author xy
 * @version 1.0
 * @description:
 * @date 2024/7/6 13:15
 */
@Service
public class AliPayServiceImpl implements IAliPayService {
    @Autowired
    private AliPayConfig aliPayConfig;

    @Resource
    private BillInfoMapper mapper;

    @Override
    public String keyPayment(AliPayDTO dto, String productCode,String notifyUrl) {
        Long billInfoId = dto.getBillId();
        // 查询账单用电量
        BillUsageVo billUsageDto = mapper.selectBillUsage(billInfoId);
        // 计算电费
        float billAmounts = MyMath.getPayAmount(billUsageDto.getLastUsage(), billUsageDto.getNowUsage());
//        float billAmounts = 0.01F;

        // 配置客户端
        AlipayClient alipayClient = new DefaultAlipayClient(aliPayConfig.getAlipayGateWay(),
                aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(),
                "json",
                "utf-8",
                aliPayConfig.getAlipayPublicKey(),
                "RSA2");
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
//        AlipayTradeWapPayRequest  request = new AlipayTradeWapPayRequest();

        // 支付流水账单号
        Long generatePkId = MyMath.generatePkId();
        // 异步回调接口地址
        request.setNotifyUrl(notifyUrl);

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", generatePkId);
        bizContent.put("total_amount", billAmounts);
        bizContent.put("subject", "账单支付");
        bizContent.put("product_code", productCode);
        bizContent.put("qr_pay_mode", 2);

        request.setBizContent(bizContent.toString());

        try {
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "GET");
            String pageRedirectionData = response.getBody();
            if (response.isSuccess()) {
                return pageRedirectionData;
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }
}
